import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

import { itemsArr } from '../components/Menu';

export interface IndexModelState {
  title: string;
}

export interface IndexModelType {
  namespace: 'admin';
  state: IndexModelState;
  effects: {
    // query: Effect;
  };
  reducers: {
    // save: Reducer<IndexModelState>;
    // 启用 immer 之后
    // save: ImmerReducer<IndexModelState>;
    changeTitle: Reducer;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'admin',

  state: {
    title: '',
  },

  effects: {
    // *query({ payload }, { call, put }) {},
  },
  reducers: {
    // save(state, action) {
    //   return {
    //     ...state,
    //     ...action.payload,
    //   };
    // },
    changeTitle(state, action) {
      return {
        ...state,
        title: action.title,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        itemsArr.forEach((item: any) => {
          if ('/admin' + item.key === pathname) {
            dispatch({ type: 'changeTitle', title: item.title });
          }
          item.children &&
            item.children.forEach((child: any) => {
              if ('/admin' + child.key === pathname) {
                dispatch({ type: 'changeTitle', title: child.title });
              }
            });
        });
      });
    },
  },
};

export default IndexModel;
